package main

import (
	"fmt"
	"log"
	"time"
)

func main() {
	// 1 time.Now()返回的是time.Time类型 自身的string()方法格式化为2018-05-20 11:49:47.952339002 +0800 CST
	fmt.Printf("1.%s\n", time.Now())

	time.Sleep(1e9) //sleep 1 sec
	// 2 time.Time ->格式化string ，注意这里必须是go的诞生日
	fmt.Printf("\n2.localtime: %s\n", time.Now().Format("2006-01-02 15:04:05"))
	fmt.Printf("2.UTC: %s\n", time.Now().UTC().Format("01/02<15:04:05>"))

	var mon time.Month
	var y, d int
	y, mon, d = time.Now().Date()
	var h, m, s int = time.Now().Clock()
	fmt.Printf("2. time.Time.Date() %d-%d-%d, time.Time.Clock() %d:%d:%d \n", y, mon, d, h, m, s)

	time.Sleep(time.Second) //sleep 1 sec
	// 3 string->time.Time (使用time.Date)
	var t time.Time
	t = time.Date(2018, 5, 1, 11, 11, 11, 0, time.Local)
	fmt.Printf("\n3.time.Date(xxx).String(): %s\n", t.String())

	// 3 string->time.Time (使用time.Parse)
	t, err := time.Parse("2006-01-02 15:04:05", "1986-12-26 10:30:02")
	if err != nil {
		log.Fatal("err")
	}
	fmt.Printf("3.time.Parse(xxxxx).String(): %s\n", t.String())

	// 4 time.Time -> Unix Epoch
	fmt.Printf("\n4 Time->Unix Epoch, time.Now().Unix() = %d\n", time.Now().Unix())
	fmt.Printf("4 Time->Unix Epoch nanosec, time.Now().UnixNano() = %d\n", time.Now().UnixNano())

	// 5 time.Timer
	var ct time.Time
	i := 0
	h, m, s = time.Now().Clock()
	fmt.Printf("\n5 New time.Timer, cur time %d:%d:%d, 5 seconds\n0", h, m, s)
	var tr *time.Timer = time.NewTimer(time.Second * 5)
	for i >= 0 {
		select {
		case ct = <-tr.C:
			fmt.Printf("\r%d %d:%d:%d\n", i, ct.Hour(), ct.Minute(), ct.Second())
			i = -1
		default:
			fmt.Printf("\r%d", i)
			i++
			time.Sleep(time.Second)
		}
	}

	// 6 time.Duration
	dr, _ := time.ParseDuration("3m20s")
	fmt.Printf("\n6 3m20s = %.2fSeconds\n", dr.Seconds())

	fmt.Println("\n7 clock")
	var now time.Time = time.Now()
	exptime := now.Add(time.Second * 5)
	for time.Now().Before(exptime) {
		fmt.Printf(time.Now().Format("\r15:04:05"))
		time.Sleep(time.Second)
	}
	fmt.Printf("\n")

	fmt.Printf("\n8 time.Tick(time.Duration)\n")
	tick := time.Tick(time.Second)
	for i := 5; i > 0; i-- {
		fmt.Printf("\r%d", i)
		<-tick
	}
	fmt.Printf("\r\n")

}
